<script setup>
import {ref, defineProps, defineEmits, computed, watch} from 'vue'
import { useRouter } from 'vue-router'
import { formatDate, getFourDays, getRangeDays } from '@/utils/index.js'
import { showToast } from 'vant'
import { isTimePassed } from '@/utils/time.js'
import api from "@/api/index.js"

const router = useRouter()
const emit = defineEmits(['closePopup'])
const props = defineProps({
  showPopup: Boolean,
  sessionlist: Object,
  scenicId: String,
  sortid: String,
  title: String,
  marketPrice: Number,
  productid: String,
  buyLimitCountvalue: Number,
  kindsId: String,
  goodsInfoList: Array
})
const maxvalue = ref(props.buyLimitCountvalue)

const number = ref(1)

const price = ref(props.marketPrice)
const allPrice = ref(price.value)
const showTime = ref(false)

const minDate = ref(null)
const maxDate = ref(null)

const loading = ref(true)
const ticket = ref({})
const getTicketDetail = () => {
  const params = {
    id: ticketTypes.value,
    kindsId: props.kindsId
  }
  loading.value = true
  api.getScenicSpotid(params).then((res) => {
    ticket.value[params.id] = res.data.goodsInfoVo
    const { validStartTime, validEndTime } = res.data.goodsInfoVo
    if (validStartTime) {
      minDate.value = new Date(validStartTime)
      maxDate.value = new Date(validEndTime)
    } else {
      const currentDate = new Date()
      minDate.value = currentDate
      const tenDaysLater = new Date(currentDate)
      tenDaysLater.setDate(currentDate.getDate() + 30)
      maxDate.value = tenDaysLater
    }
    const {list, more} = getRangeDays(minDate.value, maxDate.value)
    timeList.value = list ?? []
    if (props.sessionlist.length) {
      const allIsTimePassed = props.sessionlist.every(item => item.isTimePassed)
      timeList.value.forEach((item) => {
        if (item.name === '今天' && allIsTimePassed) {
          item.disabled = true
        }
      })
      if (timeList.value[0]?.disabled) {
        timeKey.value = timeList.value[1]?.yearTime
        session.value = props.sessionlist[0].id
      } else {
        timeKey.value = timeList.value[0]?.yearTime
      }
    } else {
      timeKey.value = timeList.value[0]?.yearTime
    }
    timeShowMore.value = more
  }).finally(() => {
    loading.value = false
  })
}

// const calendarMinDate
const numberChange = (e) => {
  if(e === props.buyLimitCountvalue) {
    showToast(`限购${maxvalue.value}张`)
  }
  allPrice.value = (price.value * 10000) * e / 10000
}

const overlimit = (e) => {
  if (e === 'plus') {
    if (stepperMax.value === number.value) {
      if (props.sessionlist.length) {
        if (stockCount.value < maxvalue.value) {
          showToast(`库存仅${stockCount.value}张`)
          return
        }
      }
      showToast(`限购${maxvalue.value}张`)
    }
  }
}

const ticketTypes = ref('')
const ticketTypesClick = (item) => {
  if (item.buyType) {
    maxvalue.value = item.buyLimitCount
  } else {
    maxvalue.value = 99
  }
  price.value = item.marketPrice
  ticketTypes.value = item.id
  allPrice.value = (item.marketPrice * 10000) * number.value / 10000
  getTicketDetail()
}

const stockCount = ref(0)
const sessionClick = (item) => {
  if (item.isTimePassed && isToday.value) {
    return
  }
  stockCount.value = item.stockCount
  session.value = item.id
}

const stepperMax = computed(() => {
  if (props.sessionlist.length) {
    if (stockCount.value < maxvalue.value) {
      return stockCount.value
    }
  }
  return maxvalue.value
})

watch(stepperMax, () => {
  if (!stepperMax.value) {
    number.value = 0
  }
})

const timeList = ref([])
const timeKey = ref('')
const timeKeyDate = computed(() => new Date(timeKey.value)) // 将日期字符串转换为日期对象
const timeChangeClick = (item) => {
  if (item.disabled) {
    return
  }
  timeKey.value = item.yearTime
  const temp = props.sessionlist.find(item => item.id === session.value)
  if (isToday.value && temp?.isTimePassed) {
    initSession()
  }
}

const isToday = computed(() => {
  const temp = timeList.value.find(item => item?.yearTime === timeKey.value)
  return temp?.name === '今天'
})

const timeShowMore = ref(true)
const selectChange = (data) => {
  const time = formatDate(data)
  const repeat = timeList.value.some((item) => {
    return item.yearTime === time.yearTime
  })
  if (!repeat) {
    const len = timeList.value?.length
    timeList.value[len - 1] = time
  }
  timeKey.value = time.yearTime
  showTime.value = false
}

const bookClick = () => {
  if (!stepperMax.value) {
    if (!maxvalue.value) {
      showToast("暂无库存")
      return
    }
  }
  // console.log('门票种类id', ticketTypes.value, '场次id', session.value, '日期', timeKey.value, '景区id', props.scenicId, "商品id", ticketTypes.value);
  if (!timeList.value.length) {
    showToast("暂无可预订日期")
    return
  }
  if (!ticketTypes.value) {
    showToast("未选择种类")
  } else if (!timeKey.value) {
    showToast("未选择日期")
  } else {
    router.push({
      path: '/scenicordel', query: {
        dateS: timeKey.value,
        vanum: number.value,
        scenicId: props.scenicId,  //景点id
        productid: ticketTypes.value, //商品id
        ticketTypes: props.sortid,//分类id
        sessionid: session.value, //场次id
        numberMax: stepperMax.value
      }
    })
  }
}

const useOpenAndClose = () => {
  const session = ref('')
  const initSession = () => {
    for(let item of props.sessionlist) {
      if (!item.isTimePassed) {
        session.value = item.id
        break
      }
    }
  }
  const closeBookPopup = () => {
    if (showTime.value) {
      showTime.value = false
    } else {
      emit('closePopup')
    }
  }

  const openPopup = () => {
    if (props.sessionlist?.length > 0) {
      props.sessionlist.forEach((item) => {
        item.isTimePassed = isTimePassed(item.endTime)
      })
      stockCount.value = props.sessionlist[0].stockCount
      initSession()
    }
    ticketTypes.value = props.productid
    getTicketDetail()
  }

  const moreTimeClick = () => {
    showTime.value = true
  }

  const closeCalendarClick = () => {
    showTime.value = false
  }
  return { session, closeBookPopup, openPopup, moreTimeClick, closeCalendarClick, initSession }
}

const { session, closeBookPopup, openPopup, moreTimeClick, closeCalendarClick, initSession } = useOpenAndClose()
</script>

<template>
  <van-popup
    teleport="body"
    class="van_popup"
    :style="{ 'max-height': '70vh' }"
    v-model:show="props.showPopup"
    round
    position="bottom"
    :close-on-click-overlay="false"
    @click-overlay="closeBookPopup"
    @open="openPopup"
  >
    <div class="box" v-show="!showTime">
      <div class="header">
        <div class="name">{{ props.title }}</div>
        <img @click="closeBookPopup" class="close" src="@/assets/images/icons/close-666666.png" alt="">
      </div>
      <div class="content">
        <div class="content_top">
          <div class="type" v-if="goodsInfoList?.length">
            <div class="name">门票种类</div>
            <div class="button_list">
              <div v-for="item in goodsInfoList" :key="item.id" @click="ticketTypesClick(item)"
                class="button" :class="{ 'action_button': ticketTypes === item.id, }">
                {{ item.ticketName }}
              </div>
            </div>
          </div>
          <div class="type" v-if="props.sessionlist?.length > 0">
            <div class="name">场次</div>
            <div class="button_list">
              <div v-for="item in props.sessionlist" :key="item.id" @click="sessionClick(item)" class="button"
                :class="{ 'action_button': session === item.id, 'button_disabled': item.isTimePassed && isToday }">
                {{ item.beginTime }}-{{ item.endTime }}
              </div>
            </div>
          </div>
          <div class="time">
            <div class="name">使用日期</div>
            <div class="time_list">
              <template v-if="!loading">
                <template v-if="timeList.length">
                  <div
                    @click="timeChangeClick(item)"
                    v-for="item in timeList"
                    :key="item.yearTime"
                    class="time_button"
                    :class="{ 'time_button_action': timeKey === item.yearTime, 'time_button_disabled': item.disabled}"
                  >
                    <div class="top">{{ item.name }}</div>
                    <div class="bottom">{{ item.time }}</div>
                  </div>

                  <div v-if="timeShowMore" class="time_button more" @click="moreTimeClick">
                    <div class="top">更多</div>
                    <div class="bottom">日期</div>
                  </div>
                </template>
                <div v-else class="time_none">暂无可预订日期</div>
              </template>
              <van-skeleton v-else>
                <template #template>
                  <div :style="{ display: 'flex', width: 'calc(100vw - 4rem)', height: '5.1rem' }">
                    <div :style="{ flex: 1, display: 'flex', 'align-items': 'center', 'justify-content': 'space-between'}">
                      <van-skeleton-paragraph row-width="17.5%" />
                      <van-skeleton-paragraph row-width="17.5%" />
                      <van-skeleton-paragraph row-width="17.5%" />
                      <van-skeleton-paragraph row-width="17.5%" />
                      <van-skeleton-paragraph row-width="17.5%" />
                    </div>
                  </div>
                </template>
              </van-skeleton>


            </div>
          </div>
          <div class="number">
            <div class="name">购买数量</div>
            <van-stepper
              v-model="number"
              integer
              :max="stepperMax"
              :disabled="!stepperMax"
              @change="numberChange"
              @overlimit="overlimit"
            />
          </div>
        </div>
      </div>
      <div class="popup_bottom">
        <div class="button_box">
          <div class="book_button" :class="{'book_button_disabled': !stepperMax}" @click="bookClick">预订</div>
          <div class="price">
            <span class="icon">￥</span>
            <span class="price_number">{{ allPrice }}</span>
          </div>
          <div class="text">应付金额：</div>
        </div>
      </div>
    </div>
    <div class="calendar_box" v-show="showTime">
      <div class="header">
        <div class="name">使用日期</div>
        <img @click="closeCalendarClick" class="close" src="@/assets/images/icons/close-666666.png" alt="">
      </div>
      <van-calendar
        v-if="!loading"
        v-show="showTime"
        :default-date="timeKeyDate"
        :show-title="false"
        :show-subtitle="false"
        :poppable="false"
        :show-confirm="false"
        :style="{ maxHeight: 'calc(70vh - 6.3rem)' }"
        :min-date="minDate"
        :max-date="maxDate"
        row-height="3rem"
        @select="selectChange"
      />
    </div>
  </van-popup>
</template>

<style scoped lang="scss">
:deep(.van-skeleton) {
  padding: 0;
}
:deep(.van-skeleton-paragraph) {
  width: 6.5rem;
  height: 5.1rem;
}
:deep(.van-skeleton-paragraph:not(:first-child)) {
  margin-top: 0;
}

@mixin header {
  height: 2.8rem;
  margin-top: 2rem;
  justify-content: space-between;
  display: flex;
  margin-bottom: 1.5rem;

  .name {
    font-size: 2rem;
    font-weight: bold;
    color: #2F3836;
  }

  .close {
    width: 1.6rem;
    height: 1.6rem;
  }
}
.box {
  padding: 0 2rem;
  display: flex;
  flex-direction: column;
  .header {
    @include header;
  }

  .content {
    max-height: calc(70vh - 2rem - 2.8rem - 1.5rem - 9rem);
    display: flex;
    flex-direction: column;
    overflow-y: auto;

    .content_top {
      padding-top: .5rem;
      flex: 1;
    }
  }

  .popup_bottom {
    height: 9rem;

    .button_box {
      padding-top: 1rem;
      display: flex;
      flex-direction: row-reverse;
      align-items: center;

      .book_button {
        height: 3.8rem;
        line-height: 3.8rem;
        background: var(--van-primary-color);
        border-radius: .5rem;
        font-size: 1.6rem;
        color: #FFFFFF;
        padding: 0 3rem;
        margin-left: 1rem;
      }

      .book_button:active {
        background: #4b947f;
      }
      .book_button_disabled {
        opacity: 0.5;
      }

      .price {
        color: #ED6316;
        overflow: hidden;

        .icon {
          font-size: 1.4rem;
        }

        .price_number {
          font-size: 2.2rem;
        }
      }

      .text {
        font-size: 1.4rem;
        color: #999999;
      }
    }
  }

  .type {
    margin-bottom: 2rem;

    .name {
      font-size: 1.4rem;
      color: #999999;
      line-height: 1.6rem;
      margin-bottom: 1rem;
    }

    .button_list {
      display: flex;
      flex-wrap: wrap;

      .button {
        height: 3rem;
        background: rgba(0, 0, 0, 0.05);
        border-radius: .5rem;
        font-size: 1.4rem;
        color: #666666;
        line-height: 3rem;
        text-align: center;
        padding: 0 1.5rem;
        margin-right: 1rem;
        margin-bottom: 1.5rem;
      }

      .action_button {
        color: #FFFFFF;
        background: var(--van-primary-color);
      }
      .button_disabled{
        opacity: 0.5;
      }
    }
  }

  .time {
    .name {
      font-size: 1.4rem;
      color: #999999;
      line-height: 1.6rem;
      margin-bottom: 1rem;
    }

    .time_list {
      display: flex;
      padding-bottom: 2rem;
      border-bottom: .1rem solid #EEEEEE;

      .time_button {
        width: 6.5rem;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        text-align: center;
        height: 5.1rem;
        background: rgba(0, 0, 0, 0.05);
        border-radius: .5rem;
        font-size: 1.2rem;
        color: #666666;
        margin-right: 1rem;
        .top {
          margin-bottom: .3rem;
        }

        .button {
          margin-top: .3rem;
        }
      }

      .time_button_action {
        background-color: Var(--van-primary-color);
        color: #FFFFFF;
      }
      .time_button_disabled {
        opacity: 0.5;
      }

      .time_button_disabled {
        color: #BBBBBB;
      }

      .more {
        color: var(--van-primary-color);
        width: 5.4rem;
      }
      .time_none {
        width: 100%;
        height: 5.1rem;
        line-height: 5.1rem;
        text-align: center;
        font-size: 1.4rem;
        color: #666666;
      }
    }
  }

  .number {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 2rem;
    margin-bottom: 4rem;

    .name {
      font-size: 1.4rem;
      color: #999999;
    }
  }

}

.calendar_box{
  .header{
    @include header;
    padding: 0 2rem;
  }
}

</style>